//
//  WKTextFieldExtension.swift
//  商家端Swift
//
//  Created by 天下宅 on 16/9/12.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import Foundation
import UIKit

private var wkMaxCountKey = "wkMaxCount"
extension UITextField
{
    var wkMaxCount:Int
        {
        set(newValue){
            objc_setAssociatedObject(self, &wkMaxCountKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            
        }
        
        get{
            var count = (objc_getAssociatedObject(self, &wkMaxCountKey) ?? 0) as! Int
            if count < 0 {count = 0}
            return count
        }
    }
    
    func enableMaxCount()
    {
        self.addTarget(self, action: #selector(textChanged), for: UIControlEvents.editingChanged)
    }
    
    func disableMaxCount()
    {
        self.removeTarget(self, action: #selector(textChanged), for: UIControlEvents.editingChanged)
    }
    
    func textChanged()
    {
        if wkMaxCount > 0
        {
            if (self.text?.characters.count)!  > wkMaxCount
            {
                let startIndex = self.text!.startIndex
                
                self.text = self.text!.substring(to: self.text!.index(startIndex, offsetBy: wkMaxCount))
            }
        }
    }
    

}
